<html>
    <head>
        <title>Itowns - Oriented image</title>

        <script type="importmap">
        {
            "imports": {
                "itowns": "../dist/itowns.js",
                "debug": "../dist/debug.js",
                "dat": "https://unpkg.com/dat.gui@0.7.9/build/dat.gui.module.js",
                "GuiTools": "./jsm/GUI/GuiTools.js",
                "LoadingScreen": "./jsm/GUI/LoadingScreen.js",
                "itowns_widgets": "../dist/itowns_widgets.js",
                "OrientedImageHelper": "./jsm/OrientedImageHelper.js",
                "three": "https://unpkg.com/three@0.170.0/build/three.module.js",
                "three/addons/": "https://unpkg.com/three@0.170.0/examples/jsm/"
            }
        }
        </script>
        <link rel="stylesheet" type="text/css" href="css/example.css">
        <style type="text/css">
            #info {
                color: black;
                position: absolute;
                bottom: 0;
                right: 0;
                margin-right: 15px;
                padding: 0.3rem;
                background-color: rgba(255, 255, 255, 0.493);
                border: 2px solid black;
                border-radius: 5px;
            }
        </style>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <div id="viewerDiv">
            <p id="info">
                Picture taken by Walter Mittelholzer in 1919, metadata from
                <a href="https://smapshot.heig-vd.ch/map/?imageId=2873" target="_blank"> smapshot.heig-vd.ch </a>
            </p>
        </div>
        <script type="module">

            import GuiTools from 'GuiTools';
            import setupLoadingScreen from 'LoadingScreen';
            import * as THREE from 'three';
            import * as itowns from 'itowns';
            import * as debug from 'debug';
            import * as itowns_widgets from 'itowns_widgets';
            import OrientedImageHelper from 'OrientedImageHelper';

            // Define initial camera position.
            // Note that camera initial position will be overwritten by picture position later
            // var dummyPositionOnGlobe = { longitude: 0, latitude: 0, altitude: 10000000 };
            var placement = {
                coord: new itowns.Coordinates('EPSG:4326', 0, 0),
                range: 10000000,
            }

            // `viewerDiv` will contain iTowns' rendering area (`<canvas>`)
            var viewerDiv = document.getElementById('viewerDiv');

            // Instanciate iTowns GlobeView*
            var view = new itowns.GlobeView(viewerDiv, placement, {
                sseSubdivisionThreshold: 6,
                noControls: true,
            });

            var pictureInfos;
            var coord;
            var rotationMatrix;
            // eslint-disable-next-line no-unused-vars
            var plane;
            var camera;

            // Add one imagery layer to the scene
            // This layer is defined in a json file but it could be defined as a plain js
            // object. See Layer* for more info.
            itowns.Fetcher.json('./layers/JSONLayers/Ortho.json').then(function _(config) {
                config.source = new itowns.WMTSSource(config.source);
                var layer = new itowns.ColorLayer('Ortho', config);
                view.addLayer(layer).then(menuGlobe.addLayerGUI.bind(menuGlobe));
            });

            // Add two elevation layers.
            // These will deform iTowns globe geometry to represent terrain elevation.
            function addElevationLayerFromConfig(config) {
                config.source = new itowns.WMTSSource(config.source);
                var layer = new itowns.ElevationLayer(config.id, config);
                view.addLayer(layer).then(menuGlobe.addLayerGUI.bind(menuGlobe));
            }
            itowns.Fetcher.json('./layers/JSONLayers/IGN_MNT_HIGHRES.json').then(addElevationLayerFromConfig);
            itowns.Fetcher.json('./layers/JSONLayers/WORLD_DTM.json').then(addElevationLayerFromConfig);

            pictureInfos = {
                panoramic: {
                    latitude: 45.9228208442959,
                    height: 4680.55588294683,
                    longitude: 6.83256920100156,
                    azimuth: 526.3900321920207,
                    roll: 2.1876227239518276,
                    tilt: -11.668910605126001,
                    image: 'http://www.itowns-project.org/itowns-sample-data/images/MontBlanc/MontBlanc.jpg',
                },
                camera: {
                    // size of the picture in pixel
                    size: [6490, 4408],
                    // focal length in pixel
                    focal: 8270,
                    // Starting with ENH orientation,
                    // we will change to go to aircraft orientation,
                    // and then, to go to camera orientation.
                    //
                    // Starting from from ENH orientation ( X to east, Y to the north, Z is the vertical)
                    // We now defines the rotations referential space: Aircarft orientation
                    // We are creating the classic aircraft axis, using lookAt and Up :
                    // First we look at the north, (north is on the Y axis in ENH orientation),
                    // so Z axis will point to the north
                    enhToOrientationLookAt: new THREE.Vector3(0, 1, 0),
                    // then set the up vector to look to the ground,
                    // wich is the opposition of Z in ENH orientation, so Y axis will point to the ground.
                    enhToOrientationUp: new THREE.Vector3(0, 0, -1),
                    // after that, X axis will naturally point the east.
                    //
                    // From the previous space (X to East, Y to the ground, Z to the north),
                    // let's define the camera orientation (X to East, Y to the sky, Z to the south).
                    orientationToCameraUp: new THREE.Vector3(0, -1, 0),
                    orientationToCameraLookAt: new THREE.Vector3(0, 0, 1),
                },
                distance: 4000,
                opacity: 1,
            };

            function parseAircraftConventionOrientationToMatrix(panoramic) {
                var euler = new THREE.Euler(
                    THREE.MathUtils.degToRad(panoramic.tilt),
                    THREE.MathUtils.degToRad(panoramic.azimuth),
                    THREE.MathUtils.degToRad(panoramic.roll),
                    'ZYX');

                return new THREE.Matrix4().makeRotationFromEuler(euler);
            }

            coord = new itowns.Coordinates('EPSG:4326', pictureInfos.panoramic.longitude, pictureInfos.panoramic.latitude, pictureInfos.panoramic.height);
            rotationMatrix = parseAircraftConventionOrientationToMatrix(pictureInfos.panoramic);

            // eslint-disable-next-line no-unused-vars
            camera = OrientedImageHelper.initCamera(view, pictureInfos.panoramic.image, coord,
                pictureInfos.camera.enhToOrientationUp, pictureInfos.camera.enhToOrientationLookAt,
                rotationMatrix,
                pictureInfos.camera.orientationToCameraUp, pictureInfos.camera.orientationToCameraLookAt,
                pictureInfos.distance,
                pictureInfos.camera.size, pictureInfos.camera.focal);


            plane = OrientedImageHelper.setupPictureFromCamera(camera, pictureInfos.panoramic.image, pictureInfos.opacity,
                pictureInfos.distance);

            OrientedImageHelper.setupViewCameraDecomposing(view, camera);

            // open view camera FOV of 10° to see landscape around the picture.
            view.camera3D.fov += 10;
            view.camera3D.updateProjectionMatrix();

            // uncomment to debug camera
            // addCameraHelper(view, camera);

            // eslint-disable-next-line no-new
            new itowns.FirstPersonControls(view);

            /* global itowns, document, GuiTools, view, promises */
            var menuGlobe = new GuiTools('menuDiv', view);
            // setup GUI
            function updatePlaneDistance() {
                OrientedImageHelper.transformTexturedPlane(camera, pictureInfos.distance, plane);
            }
            OrientedImageHelper.setupPictureUI(menuGlobe, pictureInfos, plane, updatePlaneDistance, view, 3000, 15000);

            var d = new debug.Debug(view, menuGlobe.gui);
            debug.createTileDebugUI(menuGlobe.gui, view, view.tileLayer, d);

            window.view = view;
            window.itowns = itowns;
            window.THREE = THREE;

        </script>
    </body>
</html>
